import React, { useCallback, useContext, useState } from 'react';
import '../../style.less';
import { Input } from 'antd';
import { EventsMap } from '../../shared';
import { InBizTableCtx, InBizTableRefCtx } from '../../context';
import { SearchProps } from '../../interfaces';
import { SearchOutlined } from '@ant-design/icons';

const Search = (props: SearchProps) => {
  const { searchRef } = useContext(InBizTableRefCtx);
  const { searchField, emit, modelname, relationField } = useContext(InBizTableCtx);

  const [search, setSearch] = useState(undefined);

  const getParentCondition = () => {
    const conditionList = searchRef.current.conditions;
    const result: Array<any> = [];
    conditionList?.forEach((ele) => {
      const innerCondition = ele.condition;
      const innerResult = innerCondition.filter((child) => child.field === relationField);
      if (innerResult.length !== 0) {
        result.push(...innerResult);
      }
    });
    return result;
  };

  const getSearchValues = (value) => {
    const _searchValue = (searchField || []).map((name) => {
      return {
        value,
        connector: 'or',
        field: name,
        modelName: modelname,
        operator: 'like',
      };
    });
    const parentCondition = getParentCondition();
    const searchValue =
      _searchValue.length > 0
        ? [
          {
            connector: 'and',
            index: 0,
            condition: [...parentCondition],
          },
          {
            connector: 'and',
            index: 0,
            condition: [..._searchValue],
          },
        ]
        : undefined;

    searchRef.current = {
      ...searchRef.current,
      conditions: searchValue,
    };
  };

  const onSearch = useCallback((value) => {
    getSearchValues(value);
    props?.fetchData?.();
  }, []);

  const searchHandle = () => {
    (emit as any)?.(EventsMap.onClick, 'search');
    (emit as any)?.(EventsMap.onQueryClick, 'search');
    onSearch(search);
  };

  const changeValue = (e) => {
    setSearch(e.target.value);
  };

  // SearchOutlined
  return (
    <div className="subtable-search">
      <div className="search-items">
        <Input
          value={search}
          onChange={changeValue}
          suffix={<SearchOutlined onClick={searchHandle} />}
          onPressEnter={searchHandle}
          allowClear
        />
      </div>
    </div>
  );
};

export default React.memo(Search);
